import DialogStore from ".";
import { Button, message } from 'antd';
import { each,uniqueId } from 'lodash';
import { observable, action ,toJS} from "mobx";
import { WeaForm, WeaTableNew } from 'comsMobx';
import API from '../../apis/cuspath';
import { formInfo } from '../../components/path-template/operatorData';
import { WeaLocaleProvider } from "ecCom";
const getLabel = WeaLocaleProvider.getLabel;
import { WeaTools } from "ecCom";
const fieldKeys = {
    uuid: 'uuid',
    id: 'id',
    name: 'name',
    nodeType: 'nodeType',
    operatorType: 'operatorType',
    tablename: 'tablename',
    tablekey: 'tablekey',
    showfield: 'showfield',
    hrmField:'hrmField',
    sqlWhere:'sqlWhere',
    isrecursion: 'isrecursion',
    tablesup: 'tablesup',
    relationtype: 'relationtype',
    hrmresource: 'hrmresource',
    hrmdepartment: 'hrmdepartment',
    hrmsubcompany: 'hrmsubcompany',
    rootids: 'rootids',
    supnodefield: 'supnodefield',
    nodefield: 'nodefield',
}
export default class NodeModalStore extends DialogStore {
    @observable id;
    @observable parentid;
    @observable form = new WeaForm();
    @observable operatorForm;
    @observable itemType = '0';
    @observable order = "0";
    @observable loading = false;
    @observable autoSaveVisiable = false;

    pathStore;
    @observable parentNodeType;
    @observable parentOperateType;
    @observable parentTableName;

    @observable operatorDataSource = [];

    @observable selectedRowKeysAllPages = [];

    @observable templateid;

    @observable operateMenuDialogStore

    @observable disableAll = false;

    constructor(pathStore) {
        super();
        this.pathStore = pathStore;
        this.initOperatorForm();
        this.style = { width: 720, height: 600 }
        this.hasScroll = true;
        each(fieldKeys, action((value, key) => {
            this.form.add('', { key });
            if (key === 'hreflink') {
                this.form.add('', { key: 'hreflinkType' });
                this.form.add('', { key: 'hreflinkUrl' });
            } else if (key === 'operatorType') {
                this.form.$(key).set('0');
            } 
        }));
    }
    @action init = (parentNode) => {
        this.form.resetForm();
        this.loading = true;
        this.id = '';
        this.parentid = parentNode.id;
        this.disableAll = parentNode.disableAll;
        this.form.$('nodeType').set('0');
        this.itemType = '0';
        this.parentTableName = parentNode.tablename;
        this.parentOperateType = parentNode.operatorType
        if(!parentNode.tablename) this.form.$('supnodefield').onChange('id', 'id', 'id');
        this.parentNodeType = parentNode.nodeType;
        if(this.parentNodeType==='1'){
            this.form.$('nodeType').set('1');
            this.form.$('operatorType').set('0');
            this.itemType = '6';
            this.form.$('relationtype').set('1');
        }
        if(this.parentOperateType==='3') this.form.$('operatorType').set('3');
        //this.initOperatorTable();
        this.operatorDataSource=[];
        this.initOperatorForm();
        this.buttons = [(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@uqff1q@save`} type="primary" onClick={this.save}>{getLabel(30986, '保存')}</Button>),
        (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@y405l6@cancel`} type="primary" onClick={this.hide}>{getLabel('31129', '取消')}</Button>)]
    }
    @action initOperatorTable = () => {
        this.initOperatorForm();
        //if (this.id) operatorList(this.id).then(this.setOperatorTable);
    }
    @action setOperatorTable = (data) => {
        this.operatorDataSource = data.datas;
        //this.disableAll = data.disableAll;
    }
    @action getHrmresourceDatas() {
        if (this.node) {
            return this.node.hrmresourceObj;
        }
    }
    @action initNode = (node) => {
        this.node = node;
        switch (node.nodeType) {
            case '0': this.itemType = '0'; break;
            case '1': this.itemType = '6'; break;
        }
        switch (node.operateType) {
            case '0': this.itemType = '6'; break;
            case '1': this.itemType = '7'; break;
            case '2': this.itemType = '11'; break;
            case '3': this.itemType = '15'; break;
        }
        each(fieldKeys, action((value, key) => {
            if (key === 'hrmresource') {
                const datas = node.hrmresource && node.hrmresource.valueObj || [];
                this.form.$('hrmresource').onChange(datas.map(d => d.id).join(','), '', datas);
            } else if (key === 'hrmdepartment') {
                const datas = node.hrmdepartment && node.hrmdepartment.valueObj || [];
                this.form.$('hrmdepartment').onChange(datas.map(d => d.id).join(','), '', datas);
            } else if (key === 'hrmsubcompany') {
                const datas = node.hrmsubcompany && node.hrmsubcompany.valueObj || [];
                this.form.$('hrmsubcompany').onChange(datas.map(d => d.id).join(','), '', datas);
            } else if (key === 'rootids') {
                const datas = node.operateType === '3' ? node.rootids : ''
                this.form.$('rootids').onChange(datas);
            } else if (key === 'tablename' || key === 'tablekey' || key === 'showfield' || key === 'hrmField' || key === 'tablesup' || key === 'supnodefield' || key === 'nodefield') {
                const datas = node[key] ;
                this.form.$(key).onChange(datas, datas, [{id:datas,name:datas}]);
            }else {
                this.form.$(key).set(node[value]);
            }
        }));
        this.initOperatorForm();
        this.loading = false;
    }

    $ = (name) => {
        return this.form.$(name);
    }
    @action initOperatorForm = () => {
        this.operatorForm = new WeaForm();
        const typeDetail = formInfo[this.itemType] || {};
        const items = typeDetail.items || [];
        const conditions = [{ defaultshow: true, items }];
        if (items.length > 1 && items[1].conditionType === 'SELECT_LINKAGE') {
            this.operatorForm.add('', { key: 'joblevel' });
            this.operatorForm.add('', { key: 'jobid_dept' });
            this.operatorForm.add('', { key: 'jobid_subcom' });
        }
        this.operatorForm.initFormFields(conditions);
    }
    @action changeNodeType = (value) => {
        this.form.$('nodeType').set(value);
        if (value === '0') {
            this.itemType = '0';
        } else if (value === '1') {
            this.form.$('operatorType').set('0');
            if (this.parentNodeType === '0') {
                this.form.$('relationtype').set('0');
            } else if (this.parentNodeType === '1') {
                this.form.$('relationtype').set('1');
            }
            this.itemType = '6';
        }
        this.initOperatorTable();
    }
    @action changeOperatorType = (value) => {
        this.form.$('operatorType').set(value);
        switch (value) {
            case '0': this.itemType = '6'; break
            case '1': this.itemType = '7'; break
            case '2': this.itemType = '11'; break
            case '3': this.itemType = '15'; break
        }
        this.initOperatorForm();
    }

    @action changeItemType = (value) => {
        this.itemType = value;
        this.initOperatorForm();
    }
    @action setOrder = (order) => {
        this.order = order;
    }
    @action addOperator = () => {
        const rootids = this.getParams().rootids ? this.getParams().rootids : '';
        if (this.checkOperatorParams()) {
            const name = this.operatorForm.getFormDatas().field && this.operatorForm.getFormDatas().field.valueSpan;
            const type = this.getOperatorType();
            const relationtype = this.form.$('relationtype').value
            if (relationtype === '0' && (this.itemType === '6' || this.itemType === '7' || this.itemType === '8' || this.itemType === '9' || this.itemType === '11' || this.itemType === '12' || this.itemType === '13'|| this.itemType === '16')) {
                let valueSpan = [];
                switch (this.itemType) {
                    case '6': valueSpan = this.form.$('hrmresource').valueObj; break;
                    case '16': valueSpan = this.form.$('hrmresource').valueObj; break;
                    case '7': valueSpan = this.form.$('hrmdepartment').valueObj; break;
                    case '8': valueSpan = this.operatorForm.$('field').valueObj; break;
                    case '9': valueSpan = this.operatorForm.$('field').valueObj; break;
                    case '11': valueSpan = this.form.$('hrmsubcompany').valueObj; break;
                    case '12': valueSpan = this.operatorForm.$('field').valueObj; break;
                    case '13': valueSpan = this.operatorForm.$('field').valueObj; break;
                }
                if (valueSpan && valueSpan.length > 0) {
                    const levelString = this.getLevelString();
                    if(levelString === false) {
                        message.error(getLabel('512197','请输入安全级别'));
                        return;
                    }
                    valueSpan.map(v => {
                        this.operatorDataSource = [...this.operatorDataSource, {
                            key: uniqueId('-'),
                            name: v.name,
                            type: type,
                            levelString: levelString,
                            ...this.operatorForm.getFormParams(),
                            shareType: this.itemType,
                            rootids: v.id
                        }];
                    })
                } else {
                    this.objBrowserErr.showError();
                }
            } else {
                const levelString = this.getLevelString();
                    if(levelString === false) {
                        message.error(getLabel('512197','请输入安全级别'));
                        return;
                    }
                this.operatorDataSource = [...this.operatorDataSource, {
                    key: uniqueId('-'),
                    name: name,
                    type: type,
                    levelString: this.getLevelString(),
                    ...this.operatorForm.getFormParams(),
                    shareType: this.itemType,
                    rootids: rootids
                }];
            }
            this.initOperatorForm();
        }
    }
    @action save = () => {
        this.loading = true;
        const values = this.form.values();
        each(values, (value, key) => {
            if (key === 'hrmsubcompany' || key === 'hrmdepartment' || key === 'hrmresource' || key === 'rootids') {
                const { operatorType } = values;
                const selectedKey = { '0': 'hrmresource', '1': 'hrmdepartment', '2': 'hrmsubcompany', '3': 'rootids' }[operatorType];
                if (key === selectedKey) {
                    values.rootids = values[key]
                }
            }else if(key==='sqlWhere'){
                values.sqlWhere = WeaTools.Base64.encode(values[key])
            }
        })
        if (this.checkParams(values)) {
            API.addDynamicChild({parentId:this.parentid,...values, operators: JSON.stringify(this.operatorDataSource)}).then((path)=>{
                message.success(getLabel('502231','保存成功'));
                this.pathStore.setPath(path);
                this.hide();
            });
        }
    }

    @action deleteOperator = () => {
        this.selectedRowKeysAllPages.map(key => {
            const index = this.operatorDataSource.findIndex(item => item.key === key);
            if(index !== -1){
                this.operatorDataSource.splice(index, 1);
                this.operatorDataSource = [...this.operatorDataSource];
            }
        })
        this.selectedRowKeysAllPages = [];
    }


    getParams = () => {
        const values = this.form.values();
        const diffs = {};
        each(fieldKeys, (value, key) => {
            if (values[key] !== 'value' && this.node && values[key] !== this.node[value]) {
                if (key === 'hrmsubcompany' || key === 'hrmdepartment' || key === 'hrmresource' || key === 'rootids') {
                    const { operatorType } = values;
                    const selectedKey = { '0': 'hrmresource', '1': 'hrmdepartment', '2': 'hrmsubcompany', '3': 'rootids' }[operatorType];
                    if (key === selectedKey) {
                        diffs.rootids = values[key]
                    }
                }else {
                    diffs[key] = values[key]
                }
            }
        });
        if (values['name'] == 'value') diffs['name'] = values['name']
        if(values['sqlWhere']) diffs['sqlWhere'] = WeaTools.Base64.encode(values['sqlWhere'])
        return diffs;
    }


    checkParams = (values) => {
        let flag = true;
        const { name, nodeType, relationtype, operatorType, hrmresource, hrmdepartment, hrmsubcompany, tablename, tablekey, showfield, hrmField,isrecursion, tablesup,supnodefield,nodefield } = values
        let toView = true
        if (typeof name === 'string' && name.trim() === '') {//节点名称
            if(toView){
                const dom = ReactDOM.findDOMNode(this.nodeNameErr)
                dom.scrollIntoView();
                dom.getElementsByClassName("ant-input")[0].focus();
                toView = false;
            }
            this.nodeNameErr.showError()
            flag = false;
        }
        if (nodeType==='1' && relationtype === '0') {//指定对象
            if((operatorType==='0' && hrmresource === '') || (operatorType==='1' && hrmdepartment === '') || (operatorType==='2' && hrmsubcompany === '')){
                this.objBrowserErr.showError();
                flag = false;
            }
        }
        if (operatorType === '3') {//自定义
            if (typeof tablename === 'string' && tablename.trim() === '') {
                if(toView){
                    const dom = ReactDOM.findDOMNode(this.tableNameErr)
                    dom.scrollIntoView();
                    dom.getElementsByClassName("ant-input")[0].focus();
                    toView = false;
                }
                this.tableNameErr.showError();
                flag = false;
            }
            if (typeof tablekey === 'string' && tablekey.trim() === '') {
                if(toView){
                    const dom = ReactDOM.findDOMNode(this.tableKeyErr)
                    dom.scrollIntoView();
                    dom.getElementsByClassName("ant-input")[0].focus();
                    toView = false;
                }
                this.tableKeyErr.showError();
                flag = false;
            }
            if (typeof showfield === 'string' && showfield.trim() === '') {
                if(toView){
                    const dom = ReactDOM.findDOMNode(this.showFieldErr)
                    dom.scrollIntoView();
                    dom.getElementsByClassName("ant-input")[0].focus();
                    toView = false;
                }
                this.showFieldErr.showError();
                flag = false;
            }
            if (typeof hrmField === 'string' && hrmField.trim() === '') {
                if(toView){
                    const dom = ReactDOM.findDOMNode(this.hrmFieldErr)
                    dom.scrollIntoView();
                    dom.getElementsByClassName("ant-input")[0].focus();
                    toView = false;
                }
                this.hrmFieldErr.showError();
                flag = false;
            }
            if (isrecursion === '1' && typeof tablesup === 'string' && tablesup.trim() === '') {
                if(toView){
                    const dom = ReactDOM.findDOMNode(this.tableSupErr)
                    dom.scrollIntoView();
                    dom.getElementsByClassName("ant-input")[0].focus();
                    toView = false;
                }
                this.tableSupErr.showError();
                flag = false;
            }
            if (relationtype === '1' && typeof supnodefield === 'string' && supnodefield.trim() === '') {
                if(toView){
                    const dom = ReactDOM.findDOMNode(this.supnodefieldErr)
                    dom.scrollIntoView();
                    dom.getElementsByClassName("ant-input")[0].focus();
                    toView = false;
                }
                this.supnodefieldErr.showError();
                flag = false;
            }
            if (relationtype === '1' && typeof nodefield === 'string' && nodefield.trim() === '') {
                if(toView){
                    const dom = ReactDOM.findDOMNode(this.nodefieldErr)
                    dom.scrollIntoView();
                    dom.getElementsByClassName("ant-input")[0].focus();
                    toView = false;
                }
                this.nodefieldErr.showError();
                flag = false;
            }
        }
        if(this.operatorDataSource.length==0){
            message.error(getLabel('502428', '操作者为空'));
            flag = false;
        }
        return flag;
    }

    

    checkOperatorParams = () => {
        let flag = true;
        const { field, joblevel, jobid_dept, jobid_subcom } = this.operatorForm.getFormParams()
        const shareType = this.itemType;
        if (field === '' && this.browserErr) {
            this.browserErr.showError();
            flag = false;
        }
        if (shareType === '4') {
            if ((joblevel === '0' && jobid_dept === '')) {
                this.browser2Err.showError();
                flag = false;
            } else if ((joblevel === '1' && jobid_subcom === '')) {
                this.browser3Err.showError();
                flag = false;
            }
        }
        return flag;
    }

    getOperatorType = () => {
        let type = '';
        switch (this.itemType) {
            case '0': type = getLabel('502663', '指定人'); break;
            case '1': type = getLabel('502664', '指定部门'); break;
            case '2': type = getLabel('502665', '指定分部'); break;
            case '3': type = getLabel('502666', '指定角色'); break;
            case '4': type = getLabel('502667', '指定岗位'); break;
            case '5': type = getLabel('502668', '所有人'); break;
            case '6': type = getLabel('502669', '本人'); break;
            case '16': type = getLabel('683', '安全级别'); break;
            case '7': type = getLabel('502670', '本部门'); break;
            case '8': type = getLabel('502671', '本部门角色'); break;
            case '9': type = getLabel('502672', '本部门岗位'); break;
            case '11': type = getLabel('30792', '本分部'); break;
            case '12': type = getLabel('502674', '本分部角色'); break;
            case '13': type = getLabel('502675', '本分部岗位'); break;
            case '15': type = getLabel('502677', '人力资源相关字段'); break;
        }
        return type;
    }
    getLevelString = () => {
        let levelString = "";

        if(this.operatorForm.getFormDatas().level) {
            const minNum = this.operatorForm.getFormDatas().level.value[0] === 0 ? "0" : this.operatorForm.getFormDatas().level.value[0];
            const maxNum = this.operatorForm.getFormDatas().level.value[1] === 0 ? "0" : this.operatorForm.getFormDatas().level.value[1];
            if(!minNum && !maxNum) {
                // 这五种情况是安全级别必填
                if(this.itemType === '1' || this.itemType === '2' || this.itemType === '5' || this.itemType === '7' || this.itemType === '11' || this.itemType === '16') {

                    return false;
                }
                levelString = "";
                
            } else if(!minNum && maxNum) {
                levelString = "≤" + maxNum;
            } else if(!maxNum && minNum) {
                levelString = "≥" + minNum;
            } else {
                levelString = this.operatorForm.getFormDatas().level.value[0] + '~' + this.operatorForm.getFormDatas().level.value[1];
            }
        }
        switch (this.itemType) {
            case '3':
                const rolelevel = this.operatorForm.getFormParams().rolelevel;
                levelString = rolelevel === '0' ? getLabel(502298, "部门") : rolelevel === '1' ? getLabel(502299, "分部") : getLabel('140', '总部');
                break;
            case '4':
                const joblevel = this.operatorForm.getFormParams().joblevel;
                levelString = joblevel === '0' ? getLabel('502664', '指定部门') + '(' + this.jobid_deptName + ')' : joblevel === '1' ? getLabel('502665', '指定分部') + '(' + this.jobid_subcomName + ')' : getLabel('140', '总部');
                break;
        }
        return levelString;
    }

}